export const useUserStore = defineStore(
  'userStore',
  () => {
    const name = ref('tikeyc')
    const userId = ref(1024)
    const token = ref('token')

    const loadUser = async () => {
      try {
        // const { data } = await useFetch<{ name: string, userId: number }>('/api/user')
        const { data } = await useRequest<{ name: string; userId: number }>('/api/user')
        name.value = data.value?.name || ''
        userId.value = data.value?.userId || 0
        token.value = `token-${userId.value}`
        useCookie('userId', {
          default: () => userId.value,
          // expires: new Date(Date.now() + 60 * 60 * 24 * 7 * 1000),
          maxAge: 60 * 60 * 24 * 7
        })
      } catch (error) {
        console.error('Failed to load user:', error)
      }
    }

    return {
      name,
      userId,
      token,
      loadUser
    }
  },
  {
    persist: {
      // storage: piniaPluginPersistedstate.cookies({
      //   maxAge: 60 * 60 * 24 * 7 // 7 days
      // }),
      // storage: piniaPluginPersistedstate.sessionStorage(),
      storage: piniaPluginPersistedstate.localStorage(),
      pick: ['name', 'userId']
    }
  }
)
